package com.lpj.base.id.generator.autoconfigure;

import com.lpj.base.id.generator.service.impl.provider.MachineIdProvider;
import com.lpj.base.id.generator.service.impl.provider.PropertyMachineIdProvider;
import com.robert.vesta.service.intf.IdService;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author LiPengJu
 * @date: 2020/5/5
 */
@Configuration
@EnableConfigurationProperties(IdGeneratorProperties.class)
@ConditionalOnMissingBean({IdService.class})
@AutoConfigureAfter({IdGeneratorDbAutoConfig.class})
public class IdGeneratorPropertyAutoConfig {
    private final IdGeneratorProperties properties;

    public IdGeneratorPropertyAutoConfig(IdGeneratorProperties properties) {
        this.properties = properties;
    }

    @Bean
    @ConditionalOnProperty(prefix = "service.id", name = "machine-id-provider", havingValue = "property", matchIfMissing = true)
    public IdService idPropertyService() {
        List<Long> machineIds = properties.getMachineIds();
        if (CollectionUtils.isEmpty(machineIds))
            throw new IllegalArgumentException("yaml service.id.machineIds property is not exists");
        MachineIdProvider dbMachineIdProvider = PropertyMachineIdProvider.getInstance(machineIds, properties.getType().intValue());
        return properties.getIdService(dbMachineIdProvider);
    }
}
